package com.ttmall.service.impl;

import com.ttmall.common.pojo.KindeditorPicUploadResult;
import com.ttmall.common.utils.FileSaveUtil;
import com.ttmall.service.PictureService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * Created by GalaIO on 2018/1/14.
 */
@Service
public class PictureServiceImpl implements PictureService {

    @Value("${MEDIA_ROOT}")
    private String mediaRootDir;
    private static String ITEM_PIC_PREFIX = "/images/item/";

    @Override
    public KindeditorPicUploadResult uploadItemPic(MultipartFile picFile) {
        KindeditorPicUploadResult result = new KindeditorPicUploadResult();
        result.setError(1);
        result.setMessgae("none content!");
        if (picFile.isEmpty()) {
            return result;
        }
        //上传到图片服务器
        String uploadDir = mediaRootDir + ITEM_PIC_PREFIX;
        try {
            if (!FileSaveUtil.savePic(picFile.getBytes(), picFile.getOriginalFilename(), uploadDir)) {
                throw new Exception("server saving err!");
            }
        } catch (Exception ex) {
            return result;
        }
        result.setError(0);
        result.setUrl(ITEM_PIC_PREFIX + picFile.getOriginalFilename());
        result.setMessgae("successful");
        return result;
    }

    @Override
    public ResponseEntity<byte[]> fetchFile(String url) throws IOException {
        url = new String(URLDecoder.decode(url, "utf-8"));
        File file = new File(mediaRootDir + url);
        if (!file.isFile()) {
            throw new IOException("it is not a file!");
        }
        HttpHeaders headers = new HttpHeaders();
        //通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", file.getName());
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }
}
